<template>
  <div>
    <div class="formula-head"><span class="formula-name">公式</span><span class="formula-equal">=</span></div>
    <div class="code-mirror-wrappers">
      <textarea ref="textarea" />
    </div>
  </div>
</template>
<script>
// 核心文件
import CodeMirror from './FormulaCmMode'
import 'codemirror/lib/codemirror.css'
import 'codemirror/addon/hint/show-hint'
import 'codemirror/addon/hint/show-hint.css'
import 'codemirror/addon/edit/matchbrackets'
import 'codemirror/addon/selection/active-line'
import 'codemirror/theme/idea.css'

export default {
  name: 'FormulaCodeMirror',
  props: {
    value: {
      type: String,
      default: ''
    },
    fields: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      codemirrorEditor: null
    }
  },
  mounted() {
    this.codemirrorEditor = CodeMirror.fromTextArea(this.$refs.textarea, {
      theme: 'idea',
      extraKeys: { 'Alt-/': 'autocomplete' },
      matchBrackets: true,
      mode: 'text/x-formula',
      hint: {
        completeSingle: false
      }
    })
    this.codemirrorEditor.on('change', (cm) => {
      this.$emit('change', cm.getValue())
    })
    this.codemirrorEditor.on('inputRead', () => {
      this.codemirrorEditor.showHint()
    })
    this.initValue()
  },
  methods: {
    initValue() {
      if (!this.value) {
        return
      }
      let fieldObj = {}
      this.fields.forEach((field) => {
        fieldObj[field.key] = field.label
      })
      console.log(fieldObj)
      this.codemirrorEditor.setValue(this.value)
      let cursor = { line: 0, ch: 0 }
      this.codemirrorEditor.eachLine((line) => {
        for (let i = 0; i < line.text.length; i++) {
          if (line.text.charAt(i) === '#' && line.text.charAt(i + 1) === '{') {
            cursor.ch = i
            let htmlNode = document.createElement('span')
            // 查找从指定位置开始的结束符号
            let endIndex = line.text.indexOf('}', i + 1)
            // 截取变量名
            let vModel = line.text.substring(i + 2, endIndex)
            htmlNode.innerText = fieldObj[vModel]
            htmlNode.className = 'cm-field-value'
            this.codemirrorEditor.markText(
              cursor,
              { line: cursor.line, ch: cursor.ch + vModel.length + 3 },
              {
                className: 'cm-field-value',
                replacedWith: htmlNode
              }
            )
          }
        }
        cursor.line++
      })
    },
    /**
     * 插入函数
     */
    insertFunction(funName) {
      let cursor = this.codemirrorEditor.getCursor()
      this.codemirrorEditor.replaceRange(`${funName}()`, cursor, cursor)
      this.codemirrorEditor.setCursor(cursor.line, cursor.ch + funName.length + 1)
    },
    /**
     * 插入变量
     */
    insertVariable(code, name) {
      let htmlNode = document.createElement('span')
      htmlNode.innerText = name
      htmlNode.className = 'cm-field-value'
      let cursor = this.codemirrorEditor.getCursor()
      let varName = `#{${code}}`
      this.codemirrorEditor.replaceRange(varName, cursor, cursor)
      this.codemirrorEditor.markText(
        cursor,
        { line: cursor.line, ch: cursor.ch + varName.length },
        {
          className: 'cm-field-value',
          replacedWith: htmlNode
        }
      )
      this.codemirrorEditor.focus()
    },
    getValue() {
      return this.codemirrorEditor.getValue()
    }
  }
}
</script>
<style>
.formula-head {
  background: #f3f8fb;
  height: 36px;
  line-height: 36px;
  padding: 0 10px;
  border-top-left-radius: 4px;
  border-top-right-radius: 4px;
  font-size: 12px;
}

.cm-field-value {
  margin: 1px;
  padding: 1px;
  background: #1890ff;
  color: #ffffff;
  font-weight: 50;
}

.CodeMirror-hints {
  z-index: 9999 !important;
}
</style>
